
#include "glodef.h"
#include "errlog.h"
#include "vecs.h"

#include <stdlib.h>
#include <stdio.h>
#include <string.h>


/****************************************************************************/
/* allocate and release vector */

void alloc_vec(vector *A, int N)
{
    if((A==NULL)||(N<=0))
        error_msg("Invalid data in alloc_vec.\n");
    (*A).N = N;
    (*A).X = (double*)calloc(3*N,sizeof(double));
    if((*A).X==NULL)
        error_msg("Memory allocation error in alloc_vec.\n");
    (*A).Y = (*A).X + N;
    (*A).Z = (*A).Y + N;
    return;
}

void free_vec(vector *A)
{
    if(A==NULL)
        return;
    free((*A).X);
    (*A).N = 0;
    (*A).X = (*A).Y = (*A).Z = NULL;
}

void copy_vec(const vector *S, vector *T) /* copies contents of S into T */
{
    assert((S!=NULL)&&(T!=NULL));
    assert(S->N==T->N);
    memcpy((*T).X, (*S).X, 3*(*S).N*sizeof(double));
}

void clean_vec(vector *A)
{
    assert(A!=NULL);
    memset((*A).X, 0, 3*(*A).N*sizeof(double));
}

void print_vec(vector *A, char *fname)
{
    FILE *F;
    int i;
    F=fopen(fname, "wt");
    if(F==NULL)
        return;
    for(i=0;i<A->N;i++)
        fprintf(F, "%-18.12g  %-18.12g  %-18.12g\n",
                (double) A->X[i], (double) A->Y[i], (double) A->Z[i]);
    fclose(F);
}

/****************************************************************************/
/* allocate and release scalar */

void alloc_scal(scalar *A, int N)
{
    if((A==NULL)||(N<=0))
        error_msg("Invalid data in alloc_scal.\n");
    (*A).N = N;
    (*A).F = (double*)calloc(N,sizeof(double));
    if((*A).F==NULL)
        error_msg("Memory allocation error in alloc_scal.\n");
    return;
}

void free_scal(scalar *A)
{
    if(A==NULL)
        return;
    free((*A).F);
    (*A).N = 0;
    (*A).F = NULL;
}

void copy_scal(const scalar *S, scalar *T) /* copies contents of S into T */
{
    assert(S->N==T->N);
    memcpy((*T).F, (*S).F, (*S).N*sizeof(double));
}

void clean_scal(scalar *A)
{
    assert(A!=NULL);
    memset((*A).F, 0, (*A).N*sizeof(double));
}

void print_scal(scalar *A, char *fname)
{
    FILE *F;
    int i;
    F=fopen(fname, "wt");
    if(F==NULL)
        return;
    for(i=0;i<A->N;i++)
        fprintf(F, "%-18.12g\n", (double) A->F[i]);
    fclose(F);
}

